package com.lhkj.ct.wechat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lhkj.ct.base.enums.DeleteStatus;
import com.lhkj.ct.base.enums.GlobalStatus;
import com.lhkj.ct.base.exception.ValidatedException;
import com.lhkj.ct.base.model.LoginUser;
import com.lhkj.ct.base.utils.MessageUtils;
import com.lhkj.ct.base.utils.ShiroUtil;
import com.lhkj.ct.base.utils.Validate;
import com.lhkj.ct.framework.auth.dto.WeChatBindDto;
import com.lhkj.ct.meta.modules.auth.common.enums.IdentType;
import com.lhkj.ct.meta.modules.auth.common.enums.UserType;
import com.lhkj.ct.meta.modules.auth.service.UserIdentityService;
import com.lhkj.ct.meta.modules.patient.mapper.PatientMapper;
import com.lhkj.ct.meta.modules.patient.model.entity.TblPatCardRelation;
import com.lhkj.ct.meta.modules.patient.model.entity.TblPatient;
import com.lhkj.ct.meta.modules.patient.service.PatCardRelationService;
import com.lhkj.ct.wechat.service.WxMpPersonalCenterService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *     描述：用户中心
 * </p>
 */
@Service
public class WxMpPersonalCenterServiceImpl implements WxMpPersonalCenterService {

    @Resource
    private PatientMapper patientMapper;

    @Resource
    private PatCardRelationService patCardRelationService;

    @Resource
    private UserIdentityService userIdentityService;

    /**
     * fixme 这里先使用系统内用户证件号码，后续如果医院上线可进行对接获取医院档案
     */
    @Override
    public void bindPatCardNo(WeChatBindDto vo) {
        String patIdentNo = vo.getPatIdentNo();
        LambdaQueryWrapper<TblPatient> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TblPatient::getPatIdentNo, patIdentNo)
                .eq(TblPatient::getPatName, vo.getPatName())
                .last("limit 1");
        TblPatient patient = patientMapper.selectOne(queryWrapper);
        Validate.notNull(patient, "用户不存在！");
        Validate.validState(patient.getDelFlag() == DeleteStatus.NORMAL, "用户不存在！");
        Validate.validState(patient.getStatus() == GlobalStatus.NORMAL, MessageUtils.message("user.blocked"));
        String identifier = ShiroUtil.getAuthUserInfo().getIdentifier();
        // 默认就诊卡
        TblPatCardRelation patCardRelation = TblPatCardRelation.builder()
                .identifier(identifier)
                .isDefault(false)
                .patId(patient.getId())
                // fixme 这里未对接医院系统，暂时用身份证
                .patCardNo(patient.getPatIdentNo())
                .build();
        patCardRelationService.bindPatCard(patCardRelation, false);

    }

    @Override
    public boolean unbindPatCardNo(String id) {
        TblPatCardRelation patCardRelation = patCardRelationService.getById(id);
        if (!StringUtils.equals(patCardRelation.getIdentifier(), ShiroUtil.getAuthUserInfo().getIdentifier())) {
            throw new ValidatedException("非法操作，不可解绑！");
        }
        if (patCardRelation.getIsDefault()) {
            throw new ValidatedException("默认就诊卡不可解绑！");
        }
        if (StringUtils.equals(patCardRelation.getPatId(), ShiroUtil.getAuthUserInfo().getUserId())) {
            throw new ValidatedException("不可解绑当前就诊人，请先切换就诊人！");
        }
        return patCardRelationService.removeById(id);
    }

    @Override
    public void switchPatCard(String id) {
        TblPatCardRelation patCardRelation = patCardRelationService.getById(id);
        Validate.notNull(patCardRelation, "切换失败，绑定的就诊卡不存在！");
        if (!StringUtils.equals(patCardRelation.getIdentifier(), ShiroUtil.getAuthUserInfo().getIdentifier())) {
            throw new ValidatedException("非法操作，不可切换！");
        }
        TblPatient patient = patientMapper.selectById(patCardRelation.getPatId());
        Validate.notNull(patient, "档案不存在或已被删除！");
        LoginUser authUserInfo = ShiroUtil.getAuthUserInfo();
        authUserInfo.setUserId(patient.getId());
        ShiroUtil.setUser(authUserInfo);
    }

    @Override
    public List<TblPatCardRelation> selectCardNoByUser() {
        return patCardRelationService.selectByUser();
    }

    @Override
    public boolean unbindWechat() {
        return userIdentityService.unbind(UserType.PLATFORM, IdentType.WXP, ShiroUtil.getAuthUserInfo().getIdentifier());
    }
}
